package com.kcwx.web.controller.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import com.kcwx.common.annotation.Log;
import com.kcwx.common.constant.UserConstants;
import com.kcwx.common.core.controller.BaseController;
import com.kcwx.common.core.domain.AjaxResult;
import com.kcwx.common.core.domain.entity.SysDept;
import com.kcwx.common.core.domain.entity.SysRole;
import com.kcwx.common.core.domain.entity.SysUser;
import com.kcwx.common.core.page.TableDataInfo;
import com.kcwx.common.enums.BusinessType;
import com.kcwx.common.utils.SecurityUtils;
import com.kcwx.common.utils.StringUtils;
import com.kcwx.common.utils.poi.ExcelUtil;
import com.kcwx.common.utils.PwdCheckUtil;
import com.kcwx.common.core.domain.AdminValid;

import com.kcwx.shareddomain.common.dto.DeleteDto;
import com.kcwx.shareddomain.common.dto.DelParaValid;
import com.kcwx.shareddomain.system.query.SysDeptQuery;
import com.kcwx.shareddomain.system.query.SysUserQuery;
import com.kcwx.shareddomain.system.dto.SysUserEditDto;
import com.kcwx.shareddomain.system.dto.ResetPwdDto;
import com.kcwx.shareddomain.system.dto.UserAuthRoleDto;

import com.kcwx.system.dtomap.SysUserMap;
import com.kcwx.system.service.ISysDeptService;
import com.kcwx.system.service.ISysPostService;
import com.kcwx.system.service.ISysRoleService;
import com.kcwx.system.service.ISysUserService;
import com.kcwx.system.service.ISysConfigService;

/**
 * 用户信息
 * 
 */
@Api(tags = "系统管理-用户管理")
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysUserMap sysUserMap;
    /**
     * 新增用户
     */
    @ApiOperation("新增用户")
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "新增用户", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody SysUserEditDto dto)
    {
        String minNum=String.valueOf(UserConstants.PASSWORD_MIN_LENGTH);
        String maxNum=String.valueOf(UserConstants.PASSWORD_MAX_LENGTH);
        if (!PwdCheckUtil.checkStrongPwd(dto.getPassword(),minNum,maxNum)) {
            return error(String.format("密码必须为包含数字、小写字母、大写字母、特殊符号的%s-%s位字符",minNum,maxNum));
        }
        SysUser user=sysUserMap.AddDtoToEntity(dto);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user)))
        {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        int rowsAffect=userService.insertUser(user);
        return rowsAffect>0?success():error("新增失败");
    }

    /**
     * 修改用户
     */
    @ApiOperation("修改用户")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "修改用户", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@Validated @RequestBody SysUserEditDto dto)
    {
        SysUser user=sysUserMap.EditDtoToEntity(dto);
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getId());
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user)))
        {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        int rowsAffect=userService.updateUser(user);
        return rowsAffect>0?success():error("修改失败");
    }

    /**
     * 删除用户
     */
    @ApiOperation("删除用户")
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "删除用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove")
    public AjaxResult remove(@RequestBody DeleteDto dto)
    {
        Long id=DelParaValid.validDel(dto);
        if (id.longValue()==getUserId().longValue())
        {
            return error("当前用户不能删除");
        }
        int rowsAffect=userService.deleteUserById(id,getUsername());
        return rowsAffect>0?success():error("删除失败");
    }
    /**
     * 批量删除用户
     */
    @ApiOperation("批量删除用户")
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "批量删除用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/batchRemove")
    public AjaxResult batchRemove(@RequestBody DeleteDto dto)
    {
        Long []ids=DelParaValid.validBatchDel(dto);
        if (ArrayUtils.contains(ids, getUserId()))
        {
            return error("当前用户不能删除");
        }
        int rowsAffect=userService.deleteUserByIds(ids,getUsername());
        return rowsAffect>0?success():error("删除失败");
    }
    /**
     * 分页查询
     */
    @ApiOperation("分页查询")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @Log(title = "用户分页查询", businessType = BusinessType.OTHER)
    @PostMapping("/list")
    public AjaxResult list(@RequestBody SysUserQuery user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return success(getDataTable(list));
    }
    /**
     * 根据当前用户获取角色及岗位数据
     */
    @ApiOperation("根据当前用户获取角色及岗位数据")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @Log(title = "根据当前用户获取角色及岗位数据", businessType = BusinessType.OTHER)
    @GetMapping(value = { "/" })
    public AjaxResult getInfo()
    {
        Long userId=getUserId();
        userService.checkUserDataScope(userId);
        Map<String,Object> dataInfo=new HashMap<String,Object>();
        List<SysRole> roles = roleService.selectRoleAll();
        dataInfo.put("roles", AdminValid.userIsAdmin(userId) ? roles : roleService.FilterAdminRoles(roles));
        dataInfo.put("posts", postService.selectPostAll());
        return success(dataInfo);
    }

    /**
     * 根据id获取详细信息
     */
    @ApiOperation("根据id获取详细信息")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @Log(title = "根据id获取详细信息", businessType = BusinessType.OTHER)
    @GetMapping( "/getById" )
    public AjaxResult getById(Long id)
    {
        userService.checkUserDataScope(id);
        Map<String,Object> dataInfo=new HashMap<String,Object>();
        List<SysRole> roles = roleService.selectRoleAll();
        dataInfo.put("roles", AdminValid.userIsAdmin(id) ? roles : roleService.FilterAdminRoles(roles));
        dataInfo.put("posts", postService.selectPostAll());
        //查询用户信息
        SysUser sysUser = userService.selectUserById(id);
        dataInfo.put("user", sysUser);
        dataInfo.put("postIds", postService.selectPostListByUserId(id));
        dataInfo.put("roleIds", sysUser.getRoles().stream().map(SysRole::getId).collect(Collectors.toList()));
        return success(dataInfo);
    }

    /**
     * 重置密码
     */
    @ApiOperation("重置密码")
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody ResetPwdDto dto)
    {
        SysUser user= userService.selectUserById(dto.getId());
        if(user!=null){
            userService.checkUserAllowed(user);
            userService.checkUserDataScope(user.getId());
            //获取设置的默认密码
            String defaultPwd=configService.selectConfigByKey("defaultPwd");
            user.setPassword(SecurityUtils.encryptPassword(defaultPwd));
            user.setUpdateBy(getUsername());
            int rowsAffect=userService.resetPwd(user);
            return rowsAffect>0?success():error("操作失败");
        }
        else {
            return error("用户不存在");
        }
    }

    /**
     * 状态修改
     */
    @ApiOperation("状态修改")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "修改用户状态", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getId());
        user.setUpdateBy(getUsername());
        int rowsAffect=userService.updateUserStatus(user);
        return rowsAffect>0?success():error("操作失败");
    }

    /**
     * 根据用户id获取授权角色
     */
    @ApiOperation("根据用户id获取授权角色")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @Log(title = "根据用户id获取授权角色", businessType = BusinessType.OTHER)
    @GetMapping("/getAuthRole")
    public AjaxResult getAuthRole(Long userId)
    {
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        Map<String,Object> dataInfo=new HashMap<String,Object>();
        dataInfo.put("user", user);
        dataInfo.put("roles", AdminValid.userIsAdmin(userId) ? roles :roleService.FilterAdminRoles(roles));
        return success(dataInfo);
    }

    /**
     * 用户授权角色
     */
    @ApiOperation("用户授权角色")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户授权角色", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(@RequestBody UserAuthRoleDto dto)
    {
        Long userId=getUserId();
        Long[] roleIds=dto.getRoleIds();
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @ApiOperation("获取部门树列表")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @Log(title = "获取部门树列表", businessType = BusinessType.OTHER)
    @PostMapping("/deptTree")
    public AjaxResult deptTree( @RequestBody SysDeptQuery dept)
    {
        return success(deptService.selectDeptTreeList(dept));
    }
}
